package com.think.oauth.user.utils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import com.think.common.model.CustomUser;
import com.think.common.utils.Common;
import com.think.common.utils.JSonUtil;
import com.think.common.utils.annotation.OperateType;
import com.think.common.utils.annotation.SysLog;
import com.think.oauth.user.model.OperationLog;
import com.think.oauth.user.service.OperationLogService;

@Aspect
@Component
public class SysLogAspect {
	

    @Autowired
    private OperationLogService operationLogService;


    /**
     * 设置操作日志切入点 记录操作日志 在注解的位置切入代码
     */
    @Pointcut("@annotation(com.think.common.utils.annotation.SysLog)")
    public void operLogPoinCut() {
    }

    /**
     * 正常返回通知，拦截用户操作日志，连接点正常执行完成后执行， 如果连接点抛出异常，则不会执行
     * 
     * @param joinPoint 切入点
     * @param keys      返回结果
     */
    @AfterReturning(value = "operLogPoinCut()", returning = "keys")
    public void saveOperLog(JoinPoint joinPoint, Object keys) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);

        OperationLog operlog = new OperationLog();
        try {
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            // 获取操作
            SysLog opLog = method.getAnnotation(SysLog.class);
            if (opLog != null) {
                String operModul = opLog.operModul();
                OperateType operType = opLog.operType();
                String operDesc = opLog.operDesc();
                operlog.setOperModule(operModul); // 操作模块
                operlog.setOperType(operType.getMsg()); // 操作类型
                operlog.setOperDesc(operDesc); // 操作描述
                operlog.setCreator(Common.GetCurrentAuthor().getUserId());
                operlog.setUpdator(Common.GetCurrentAuthor().getUserId());
            }
            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            // 获取请求的方法名
            String methodName = method.getName();
            methodName = className + "." + methodName;

            
            CustomUser user = Common.GetCurrentAuthor();
            // 请求的参数
            Map<String, String> rtnMap = converMap(request.getParameterMap());
            // 将参数所在的数组转换成json
            String params = JSonUtil.toJson(rtnMap);
            operlog.setOperMethod(methodName); // 请求方法
            operlog.setOperRequParam(params); // 请求参数
            operlog.setOperRespParam(JSonUtil.toJson(keys)); // 返回结果
            operlog.setOperUserId(user.getUserId()+""); // 请求用户ID
            operlog.setOperUserName(user.getUsername()); // 请求用户名称
            operlog.setOperUri(request.getRequestURI()); // 请求URI
            operationLogService.save(operlog);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

  

    /**
     * 转换request 请求参数
     * 
     * @param paramMap request获取的参数数组
     */
    public Map<String, String> converMap(Map<String, String[]> paramMap) {
        Map<String, String> rtnMap = new HashMap<String, String>();
        for (String key : paramMap.keySet()) {
            rtnMap.put(key, paramMap.get(key)[0]);
        }
        return rtnMap;
    }

    /**
     * 转换异常信息为字符串
     * 
     * @param exceptionName    异常名称
     * @param exceptionMessage 异常信息
     * @param elements         堆栈信息
     */
    public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
        StringBuffer strbuff = new StringBuffer();
        for (StackTraceElement stet : elements) {
            strbuff.append(stet + "\n");
        }
        String message = exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString();
        return message;
    }
}
